package dao

import (
	"context"
	"errors"
	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/gorm"
	"kratos-realword/internal/pojo"
)

type UserDao interface {
	CreateUser(ctx context.Context, user *pojo.User) error
	GetUserByEmail(ctx context.Context, email string) (*pojo.User, error)
}

type userDao struct {
	db  *gorm.DB
	log *log.Helper
}

func NewUserDao(db *gorm.DB, logger log.Logger) UserDao {
	return &userDao{
		db:  db,
		log: log.NewHelper(logger),
	}
}

func (dao *userDao) CreateUser(ctx context.Context, user *pojo.User) error {
	rs := dao.db.Create(user)
	if rs.Error != nil {
		return rs.Error
	}
	if rs.RowsAffected <= 0 {
		return errors.New("创建用户失败")
	}
	return nil
}

func (dao *userDao) GetUserByEmail(ctx context.Context, email string) (*pojo.User, error) {
	var user pojo.User
	rs := dao.db.Where("email = ? ", email).Find(&user)
	if rs.Error != nil {
		return nil, rs.Error
	}
	if rs.RowsAffected <= 0 {
		return nil, nil
	}
	return &user, nil
}
